import { FC, memo, useEffect } from 'react'
import { Modal, Table, message } from 'antd'
import { AccountModelState, connect, Dispatch } from 'umi'
import { useState } from 'react'
interface IProps {
  visible: boolean
  hide: () => any
  dispatch: Dispatch
  payload: {
    questionCode: string
    type: string
    batchCode: string
    grade: string
    selectedExpert: any[]
  }
  update: () => any
  accountModel: AccountModelState
}

interface DataType {
  code: string
  name: number
}

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    render: (text: Text, record: any, index: number) => {
      return <span>{(index + 1).toString().padStart(2, '0')}</span>
    }
  },
  {
    title: '账号',
    dataIndex: 'code',
    key: 'code'
  }
]

const ChooseExpert: FC<IProps> = ({
  visible,
  hide,
  dispatch,
  payload,
  accountModel,
  update
}) => {
  const { questionCode, type, batchCode, grade, selectedExpert } = payload
  const { reviewerInfo } = accountModel
  const [selectKeys, setSelectKeys] = useState<string[]>([])

  const handleCancel = () => {
    hide()
  }
  const handleOk = () => {
    dispatch({
      type: 'accountModel/function_createResource',
      payload: {
        batchCode,
        grade,
        questionCode,
        type,
        reviewerCodes: selectKeys.join(',')
      },
      callback: (response) => {
        if (response.code == 200) {
          message.success('选择专家成功')
          update()
          handleCancel()
        }
      }
    })
  }

  const ListRowSelection = {
    type: 'checkbox',
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      setSelectKeys(selectedRows.map((item) => item.code))
    },
    selectedRowKeys: selectKeys
  }
  //   获取专家信息
  const getReviewerInfo = () => {
    dispatch({
      type: 'accountModel/function_getReviewerInfo',
      payload: {
        batchCode,
        grade
      }
    })
  }
  useEffect(() => {
    if (visible) {
      getReviewerInfo()
    } else {
      setSelectKeys([])
    }
  }, [visible])
  useEffect(() => {
    if (visible) {
      const account = selectedExpert.map((item) => item.reviewerName)
      const temp = reviewerInfo
        .filter((item) => account.includes(item.name))
        .map((item: any) => item.code)
      setSelectKeys(temp)
    }
  }, [reviewerInfo])
  return (
    <>
      <Modal
        title="选择专家"
        open={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        width="68%"
        okText="确认"
        cancelText="取消"
      >
        <Table
          dataSource={reviewerInfo}
          columns={columns}
          rowKey="code"
          rowSelection={ListRowSelection}
        />
      </Modal>
    </>
  )
}

const mapStateToProps = ({
  accountModel
}: {
  accountModel: AccountModelState
}) => {
  return {
    accountModel
  }
}

export default connect(mapStateToProps)(memo(ChooseExpert))
